<template>
  <view class="container">
    <!-- 上半部分：AI大模型信息 -->
    <view class="model-section">
      <view class="model-header">
        <u-icon name="https://sadtalker.oss-cn-hangzhou.aliyuncs.com/deepseek.f974cd8d.svg" size="60" custom-prefix="custom-icon"></u-icon>
        <view class="model-info">
          <view class="model-name">DeepSeek AI</view>
          <view class="model-desc">当前使用的是系统默认提供的大模型 如需要使用自己的大模型，可点击“模型设置”按钮</view>
        </view>
      </view>
      
      <view class="model-subscription">
        <view class="subscription-row">
          <view class="subscription-info">
            <text class="info-label">订阅到期：</text>
            <text class="expire-date">{{ subscription.expireDate || '未订阅' }}</text>
          </view>
        </view>
        
        <view class="action-row">
          <u-button 
            size="small" 
            type="primary" 
            plain 
            @click="handleSubscribeClick"
            class="action-btn"
          >
            订阅服务
          </u-button>
        </view>
      </view>
    </view>
    
    <!-- 下半部分：提示词和知识库设置 -->
    <view v-if="subscription.expireDate" class="settings-section">
      <view class="prompt-settings">
        <view class="section-title">智能体</view>
        
        <view class="prompt-type-selector flex">
          <u-radio-group 
            v-model="form.promptType" 
            @change="changePromptType"
            class="radio-group"
          >
		  <view class="radio-item"
			     v-for="(item, index) in promptTypes" >
			   <u-radio 
			     :key="index" 
			     :name="item.value"
			     :label="item.label"
			   ></u-radio> 
		  </view>
          </u-radio-group>
        </view>
          
        <u-textarea 
          v-model="form.promptContent" 
          placeholder="请输入提示词内容" 
          height="200"
          class="prompt-textarea"
        ></u-textarea>
        
        <view class="action-buttons">
			<view class="bottom-btn">
				<u-button 
				  type="primary" 
				  @click="editAgent"
				>
				  保存智能体
				</u-button>
			</view>
			<view class="bottom-btn">
				<u-button 
				  type="info" 
				  plain 
				  @click="manageKnowledgeBase"
				  class="bottom-btn"
				>
				  管理知识库
				</u-button>
			</view>
        </view>
      </view>
    </view>
    
    <!-- 订阅弹窗 -->
    <u-popup 
      :show="showSubscribe" 
      mode="center" 
      border-radius="20"
    >
      <view class="subscribe-popup">
        <view class="popup-header">
          <text class="title">选择订阅时长</text>
          <u-icon name="close" @click="showSubscribe = false"></u-icon>
        </view>
        
        <u-radio-group 
          v-model="selectedDuration" 
          @change="changeDuration"
        >
          <view 
            class="duration-item" 
            v-for="(item, index) in durationOptions" 
            :key="index"
          >
            <u-radio 
              :name="item.duration" 
              :label="item.durationDisplay"
            ></u-radio>
          </view>
        </u-radio-group>
        
        <view class="total-price">
          总计：<text class="price">¥{{ selectedPrice }}</text>
        </view>
        
        <u-button 
          type="primary" 
          shape="circle" 
          @click="confirmSubscribe"
        >
          确认订阅
        </u-button>
      </view>
    </u-popup>
		<u-toast ref="toast"></u-toast>
  </view>
</template>

<script>
	import api from "@/api/api";
export default {
  data() {
    return {
      subscription: {
        expireDate: ""
      },
      form: {
        promptType: 'default',
        promptContent: '你是一名销售，为客户提供产品咨询相关的问题，推荐符合其要求的产品或者解决方案，同时尽可能获得客户的联系方式'
      },
      promptTypes: [
        { label: '智能销售', value: 'default' },
        { label: '智能客服', value: 'customer-service' }
      ],
      showSubscribe: false,
      selectedDuration: 3,
      selectedPrice: 10,
	  selectedSubscriptionPlanId: null,
      durationOptions: [
      ],
      promptContents: {
        'default': '你是一名销售，为客户提供产品咨询相关的问题，推荐符合其要求的产品或者解决方案，同时尽可能获得客户的联系方式',
        'customer-service': '你是一名客服人员，为客户解答产品使用相关的问题，对于解答不了的问题，推荐他联系自己的销售专员。'
      }
    }
  },
  onLoad() {
	this.loadSubscriptionPlanList()
	this.loadWechatUserInfo()
  },
  methods: {
	loadSubscriptionPlanList() {
		this.depot.get(api.aiCard("subscriptionPlan/list"), null).
		then(response => {
			console.log(response)
			if (response && response.data && response.data.data) {
				this.durationOptions = response.data.data;
				this.selectedDuration = this.durationOptions[0].duration;
				this.selectedSubscriptionPlanId = this.durationOptions[0].id;
			}
		})
	},
	loadWechatUserInfo() {
		this.depot.get(api.aiCard("wechatUser/findWechatUserByOpenId?openId=" + uni.getStorageSync("openId"))).
		then(res => {
			let expireData = res && res.data && res.data.data && res.data.data.chatAssistantSubscriptionEndTime ? res.data.data.chatAssistantSubscriptionEndTime : null;
			this.subscription.expireDate = expireData && expireData.length > 10 ? expireData.substring(0, 10) : expireData;
		})
	},
    handleSubscribeClick() {
		console.log("in handleSubscribeClick")
      this.showSubscribe = true;
    },
    
    changeDuration(value) {
      this.selectedDuration = value;
      const selectedOption = this.durationOptions.find(item => item.duration === value);
      this.selectedPrice = selectedOption.price;
	  this.selectedSubscriptionPlanId = selectedOption.id;
    },
    
    async confirmSubscribe() {
		let vue = this;
		let response = await this.depot.post(api.aiCard("subscriptionOrder/create?planId=" + this.selectedSubscriptionPlanId))
		.catch(error => {
			this.showSubscribe = false;
			this.$refs.toast.show({
				type: "error",
				title: "提示",
				message: "发起支付失败"
			});
		})
		console.log("response",response)
		if (response && response.data && response.data.data && response.data.code === 0) {
			let payData = response.data.data;
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: payData.timeStamp,
				nonceStr: payData.nonceStr,
				package: payData.packageValue,
				signType: payData.signType,
				paySign: payData.paySign,
				success: function(res) {
					console.log(res, 'payMiniApp1');
					vue.loadWechatUserInfo();
					vue.showSubscribe = false;
				},
				fail: function(res) {
					console.log(res, 'payMiniApp2');
					vue.$refs.toast.show({
						type: "error",
						title: "提示",
						message: "支付失败",
						icon: "close-circle"
					});
				}
			});
		} else {
			this.contactUnlockModalVisible = false;
			this.$refs.toast.show({
				type: "error",
				title: "提示",
				message: "发起支付失败",
				icon: "close-circle"
			});
		}
      // this.$u.toast(`成功订阅${this.selectedDuration}个月服务`);
      // this.showSubscribe = false;
      
      // const months = parseInt(this.selectedDuration);
      // const expireDate = new Date();
      // expireDate.setMonth(expireDate.getMonth() + months);
      // this.subscription.expireDate = this.$u.timeFormat(expireDate, 'yyyy-mm-dd');
    },
    
    navigateToModelSettings() {
		this.$refs.toast.show({
			title: "提示",
			message: "该功能即将发布，敬请期待~"
		});
      // uni.navigateTo({
      //   url: '/pages/model-settings/index'
      // });
    },
    
    changePromptType(value) {
      this.form.promptContent = this.promptContents[value] || '';
    },
    
    async editAgent() {
      if (!await this.isSubscriptionExpired()) {
      	this.$refs.toast.show({
      		type: "success",
      		title: "提示",
      		message: "保存成功"
      	});
      } else {
      	this.$refs.toast.show({
      		type: "error",
      		title: "提示",
      		message: "请先订阅AI服务"
      	});
      }
    },
    
    async manageKnowledgeBase() {
		if (!await this.isSubscriptionExpired()) {
			uni.navigateTo({
			  url: "/pages/aiSetting/knowledge"
			});
		} else {
			this.$refs.toast.show({
				type: "error",
				title: "提示",
				message: "请先订阅AI服务"
			});
		}
    }, 
	async isSubscriptionExpired() {
		let res = await this.depot.get(api.aiCard("wechatUser/findWechatUserByOpenId?openId=" + uni.getStorageSync("openId")));
		let chatAssistantSubscriptionEndTime = res && res.data && res.data.data && res.data.data.chatAssistantSubscriptionEndTime ? res.data.data.chatAssistantSubscriptionEndTime : null;
		if (chatAssistantSubscriptionEndTime) {
				  chatAssistantSubscriptionEndTime = new Date(chatAssistantSubscriptionEndTime);
				  if (new Date().getTime() < chatAssistantSubscriptionEndTime.getTime()) {
					  return false;
				  } else {
					  return true;
				  }
		} else {
			return true;
		}
	}
  }
}
</script>

<style lang="less">
.container {
  padding: 20rpx;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.model-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .model-header {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    
    .model-info {
      margin-left: 20rpx;
      
      .model-name {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .model-desc {
        font-size: 26rpx;
        color: #666;
      }
    }
  }
  
  .model-subscription {
    .subscription-row {
      margin-bottom: 20rpx;
      
      .subscription-info {
        font-size: 28rpx;
        color: #666;
        
        .info-label {
          color: #999;
        }
        
        .expire-date {
          color: #2979ff;
          font-weight: bold;
        }
      }
    }
    
    .action-row {
      display: flex;
      justify-content: space-between;
      
      .action-btn {
        flex: 1;
        margin: 0 10rpx;
      }
    }
  }
}

.settings-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30rpx;
  }
  
  .prompt-type-selector {
    margin-bottom: 30rpx;
    
    .radio-group {
      display: flex;
      flex-wrap: wrap;
    }
    
    .radio-item {
      margin-right: 30rpx;
      margin-bottom: 20rpx;
    }
  }
  
  .prompt-textarea {
    margin-bottom: 30rpx;
  }
  
  .action-buttons {
    display: flex;
    justify-content: space-between;
	margin-top: 20rpx;
    
    .bottom-btn {
      width: 320rpx;
    }
  }
}

.subscribe-popup {
  padding: 40rpx;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40rpx;
    
    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
    
    .u-icon {
      color: #999;
    }
  }
  
  .duration-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 20rpx;
    border-bottom: 1rpx solid #f1f1f1;
    
    .price {
      color: #fa3534;
      font-weight: bold;
    }
  }
  
  .total-price {
    text-align: right;
    font-size: 32rpx;
    margin: 40rpx 0;
    
    .price {
      color: #fa3534;
      font-size: 40rpx;
      font-weight: bold;
    }
  }
  
  .u-btn {
    margin-top: 20rpx;
  }
}
</style>
